<?php

namespace models;

//如
// 1. http://www.meituan.com/jiudian/4700680/
// 2. http://sh.meituan.com/shop/2411473
// 3. http://cd.meituan.com/deal/34224767.html?acm=UmyulwbW887343335696789038.34224767.-1.34224767.1&mtt=1.s%2Fdefault.0.0.j7heycxb&cks=16296
// 4. http://www.meituan.com/meishi/119024292/
// 5. http://cd.meituan.com/deal/36714900.html
// 6. http://hotel.meituan.com/item/2532140/?ci=1505285290831&co=1505371690831#comment
use util\CommonUtil;

class MeiTuanSpider extends BaseSpider {

    // 初始化webUrl、apiUrl
    function __construct($url, $ua){
        $this->ua = $ua;
        $this->webUrl = $url;
        $url = explode('?',$url)[0];
        $id = 0;
        if(preg_match('/([0-9]+)/',$url,$matches)){
            $id = $matches[1];
        }
        if ($id != 0) {
            //$this->apiUrl = "http://www.meituan.com/ptapi/poi/getcomment?id={$id}&offset=0&pageSize=10&mode=0&starRange=&userId=&sortType=1";
            $this->apiUrl = "http://www.meituan.com/ptapi/poi/getcomment?id={$id}&offset=0&pageSize=10&mode=0&starRange=&userId=&sortType=1";
        }

    }

    // 获取评论列表，仅获取10条
    public function getComments(){

        if (empty($this->apiUrl)) return [];

        $ch = curl_init();
        $timeout = 30;
        curl_setopt ($ch, CURLOPT_URL, $this->apiUrl);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->ua);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        if(empty($file_contents)) return;
        $fileJson = json_decode($file_contents);
        $comments = $fileJson->comments;
        $arr = array();
        foreach ($comments as $comment){
            $commentTime = intval(trim($comment->commentTime) / 1000);
            $picUrlStr = '';
            if (!empty($comment->picUrls)) {
                foreach ($comment->picUrls as $picUrl) {
                    if (!empty($picUrlStr)) $picUrlStr .= ',';
                    $picUrlStr .= $picUrl->url;
                }
            }

            $obj = array();
            $obj['head'] = CommonUtil::replace2https($comment->userUrl);   //头像
            $obj['nickname'] = trim($comment->userName);  //昵称
            $obj['content'] = trim($comment->comment);    //评论内容
            $obj['reply'] = trim($comment->merchantComment);  //商家回复
            $obj['comment_time'] = date('Y-m-d H:i:s', $commentTime);   //评论时间
            $obj['pic_urls'] = $picUrlStr;   //评论图片
            $arr[] = $obj;
        }

        return $arr;

    }
	
}